<template>
  <page-container title="用户管理">
    <strong>过滤条件</strong>
    <el-row class="filter-row">
      <el-col :span="5">
        <el-select
          v-model="filterConditions.preference"
          :placeholder="labelMap.get('preference')"
          clearable
          filterable
        >
          <el-option
            v-for="(option, index) in preferenceOptions"
            :key="index"
            :label="option"
            :value="index"
          />
        </el-select>
      </el-col>
      <el-col :span="5">
        <picker
          @update:model-value="(value) => (filterConditions.school = value)"
          :fetch-list="schoolApi.fetchSchoolList"
          :placeholder="labelMap.get('school')"
          label-key="schoolname"
        ></picker>
      </el-col>
      <el-col :span="5">
        <picker
          @update:model-value="(value) => (filterConditions.major = value)"
          :fetch-list="userApi.fetchMajorList"
          :placeholder="labelMap.get('major')"
          label-key="majorName"
        ></picker>
      </el-col>
      <!-- 添加查询按钮 -->
      <el-col :span="2">
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </el-col>
    </el-row>
    <el-table :data="users" class="user-table">
      <el-table-column
        v-for="key in labelsInBrief"
        :key="key"
        :prop="key"
        :label="labelMap.get(key)"
      >
        <template v-if="key === 'details'" #default="{ row }">
          <el-button type="text" @click="showDetail(row)"> 查看详情 </el-button>
        </template>
        <template v-if="key === 'operation'" #default="{ row }">
          <el-button size="small" type="primary" @click="showForm(row)"
            >编辑</el-button
          >
          <el-button size="small" type="danger" @click="showDelete(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="用户详情"
      class="dialog user-detail-dialog"
    >
      <template #default>
        <div v-if="currentUser">
          <el-descriptions :column="2">
            <div v-for="(value, key) in currentUser">
              <el-descriptions-item
                v-if="labelMap.has(key)"
                :key="key"
                :label="labelMap.get(key)"
              >
                <span v-if="typeof value === 'boolean'">{{
                  value ? '是' : '否'
                }}</span>
                <span v-else>{{ value }}</span>
              </el-descriptions-item>
            </div>
          </el-descriptions>
        </div>
      </template>
    </el-dialog>
    <!-- 编辑用户信息对话框 -->
    <el-dialog
      v-model="formVisible"
      title="编辑用户信息"
      class="dialog user-form-dialog"
    >
      <template #default>
        <el-form :model="currentUser" label-width="80px">
          <el-form-item
            v-for="labelKey in labelsInForm"
            :key="labelKey"
            :label="labelMap.get(labelKey)"
          >
            <el-select
              v-if="labelKey === 'grade'"
              v-model="currentUser[labelKey]"
              placeholder="请选择年级"
              filterable
            >
              <el-option
                v-for="option in gradeOptions"
                :key="option"
                :label="option"
                :value="option"
              />
            </el-select>
            <el-select
              v-else-if="labelKey === 'preference'"
              v-model="currentUser[labelKey]"
              placeholder="请选择偏向"
              filterable
            >
              <el-option
                v-for="option in preferenceOptions"
                :key="option"
                :label="option"
                :value="option"
              />
            </el-select>
            <el-input
              v-else
              v-model="currentUser[labelKey]"
              :placeholder="labelMap.get(labelKey)"
            />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" @click="reviseUser">保存</el-button>
      </template>
    </el-dialog>
    <!-- 删除用户对话框 -->
    <el-dialog v-model="deleteVisible" title="删除用户" width="30%">
      <template #default>
        <div>
          确定要删除用户 <strong>{{ currentUser?.nickname }}</strong> 吗？
        </div>
      </template>
      <template #footer>
        <el-button @click="deleteVisible = false">取消</el-button>
        <el-button type="danger" @click="deleteUser">确定</el-button>
      </template>
    </el-dialog>
    <!-- Pagination controls -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </page-container>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import PageContainer from '@/components/PageContainer.vue'
import { useUserStore } from '@/stores'
import { grades, ProjectFocus } from '@/utils/enum'
import * as schoolApi from '@/api/school'
import * as userApi from '@/api/user'
import { mapUserFromBackend } from '@/types/user'
import Picker from '@/components/Picker.vue'
import { ElMessage } from 'element-plus'

const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
})
interface UserSelection {
  pageNum: number
  pageSize: number
  orientation?: number
  school?: number
  major?: number
}
const userStore = useUserStore()
async function fetchUserData(selection: UserSelection) {
  pagination.value.total = await userStore.fetchUserList(selection)
}
// Handle page size change
const handleSizeChange = (newSize: number) => {
  pagination.value.pageSize = newSize
  pagination.value.pageNum = 1 // Reset to first page
  handleSearch()
}

// Handle page number change
const handleCurrentChange = (newPage: number) => {
  pagination.value.pageNum = newPage
  handleSearch()
}
onMounted(async () => {
  // 初始化用户数据或其他必要操作
  fetchUserData(pagination.value)
})
interface User {
  id: number
  openId: string
  nickname?: string
  school: string
  major: string
  grade: string | number
  // 人设
  role: string
  // 性格
  personality: string
  // 偏向
  preference: string
  email: string
  phone: string
  introduction: string

  schoolcode: number
  gradecode: number
  majorcode: number
}
const gradeOptions = ref<string[]>(grades)
const preferenceOptions = ref<string[]>(ProjectFocus)

const labelsInBrief = ref<string[]>([
  'nickname',
  'school',
  'major',
  'preference',
  'email',
  'phone',
  'details',
  'operation',
])
const labelsInForm = ref<string[]>([
  'nickname',
  'school',
  'major',
  'grade',
  'role',
  'personality',
  'preference',
  'email',
  'phone',
  'introduction',
])
const labelMap = reactive<Map<string, string>>(
  new Map([
    ['id', 'ID'],
    ['nickname', '昵称'],
    ['school', '学校'],
    ['major', '专业'],
    ['grade', '年级'],
    ['role', '人设'],
    ['personality', '性格'],
    ['preference', '偏向'],
    ['email', '邮箱'],
    ['phone', '电话'],
    ['introduction', '介绍'],
    ['details', '详情'],
    ['operation', '操作'],
  ]),
)

const users = computed<User[]>(() => {
  const backendResponse = userStore.getUserList()
  return backendResponse.map((element) => mapUserFromBackend(element))
})
const detailVisible = ref(false)
const formVisible = ref(false)
const currentUser = ref<User | null>(null)
const showDetail = (user: User) => {
  currentUser.value = user
  detailVisible.value = true
  console.log(`查看用户详情: ${user.nickname}`)
}
const showForm = (user: User) => {
  currentUser.value = user
  formVisible.value = true
  console.log(
    `编辑用户信息: ${currentUser.value.nickname}, ${currentUser.value.school}`,
  )
}
const deleteVisible = ref(false)
const showDelete = (user: User) => {
  currentUser.value = user
  deleteVisible.value = true
  console.log(`准备删除用户: ${currentUser.value.nickname}`)
}

//修改用户信息
const reviseUser = async () => {
  try {
    console.log('当前用户数据:', currentUser.value)
    if (!currentUser.value) {
      console.error('当前用户数据为空')
      ElMessage.warning('用户数据未加载完成，请稍后再试')
      return
    }
    // 检查openId是否存在且有效
    if (!currentUser.value.openId) {
      console.error('用户数据中缺少openId:', currentUser.value)
      ElMessage.error('用户数据不完整，请刷新页面重试')
      return
    }
    //年级，学校与专业名称转code
    const schoolList = await schoolApi.fetchSchoolList(currentUser.value.school)
    const majorList = await userApi.fetchMajorList(currentUser.value.major)

    currentUser.value.schoolcode = schoolList[0].id
    currentUser.value.majorcode = majorList[0].id
    const gradeIndex = grades.indexOf(currentUser.value.grade as string)
    currentUser.value.gradecode = gradeIndex !== -1 ? gradeIndex + 1 : 0

    // 调用修改服务
    const response = await userApi.reviseUserService(currentUser.value)
    console.log('修改用户响应:', response)
    ElMessage.success('用户信息修改成功')
    console.log('成功修改用户信息')
    // 刷新用户列表
    fetchUserData(pagination.value)
  } catch (error) {
    console.error('修改用户信息失败:', error)
    ElMessage.error('修改失败，请稍后再试')
  } finally {
    formVisible.value = false
  }
}

//删除用户信息
const deleteUser = async () => {
  try {
    if (!currentUser.value) {
      console.error('当前用户数据为空')
      ElMessage.warning('用户数据未加载完成，请稍后再试')
      return
    }
    // 检查openId是否存在且有效
    if (!currentUser.value.openId) {
      console.error('用户数据中缺少openId:', currentUser.value)
      ElMessage.error('用户数据不完整，请刷新页面重试')
      return
    }
    console.log('准备删除的用户openId:', currentUser.value.openId)
    // 调用删除服务
    const response = await userApi.delUserService(currentUser.value.openId)
    console.log('删除用户响应:', response)
    // 从本地列表中移除
    const index = users.value.findIndex(
      (user) => user.id === currentUser.value!.id,
    )
    if (index !== -1) {
      users.value.splice(index, 1)
      console.log(`从本地列表删除用户: ${currentUser.value!.nickname}`)
    }
    ElMessage.success('用户删除成功')
    // 刷新用户列表
    fetchUserData(pagination.value)
  } catch (error) {
    console.error('删除用户失败:', error)
    ElMessage.error('删除失败，请稍后再试')
  } finally {
    deleteVisible.value = false
    currentUser.value = null
  }
}

const filterConditions = reactive({
  // nickname: undefined,
  preference: undefined,
  school: undefined,
  major: undefined,
})

// 添加 handleSearch 方法
const handleSearch = () => {
  console.log('搜索条件:', filterConditions)
  const selection: UserSelection = {
    pageNum: pagination.value.pageNum,
    pageSize: pagination.value.pageSize,
    ...(filterConditions.preference !== undefined && {
      orientation: filterConditions.preference,
    }),
    ...(filterConditions.school && {
      school: filterConditions.school,
    }),
    ...(filterConditions.major && {
      major: filterConditions.major,
    }),
  }

  fetchUserData(selection)
}
</script>

<style scoped>
.user-table {
  width: 100%;
}

.filter-row {
  margin-top: 20px;
  margin-bottom: 20px;
  column-gap: 20px;
}

.dialog {
  width: 50%;
}
</style>
